import { Request, Response } from "express";

const nfetch = require("node-fetch");
// const cfetch = require("fetch-cookie")(nfetch);
const cfetch = require("fetch-cookie/node-fetch")(nfetch);
var cookieParser = require("cookie-parser");
const Bluebird = require("bluebird");
nfetch.Promise = Bluebird;

const axios = require("axios");

var tough = require("tough-cookie");
var Cookie = tough.Cookie;
var cookiejar = new tough.CookieJar();

// let baseUrl = "http://192.168.20.13:9090";
let baseUrl = "http://api.zqd.com";

const futureUrl = "http://api.zqd.com";

interface IParams {
  baseUrl?: string;
  url: string;
  data?: any;
  type?: string;
  resType?: string;
  req?: Request;
  res?: Response;
}

// Add a request interceptor
axios.interceptors.request.use(
  function(config: any) {
    // Do something before request is sent
    const futureList: Array<string> = [
      "config",
      "sliderCode/register-fullpage",
      "user/hasUser"
    ];
    if (futureList.indexOf(config.url) !== -1) {
      config.baseURL = futureUrl;
    }

    // cookiejar.getCookies(config.url, function(err: any, cookies: any) {
    // config.headers.cookie = cookies.join("; ");
    // console.log(req.cookies, 44444);
    // });

    return config;
  },
  function(error: any) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
axios.interceptors.response.use(
  function(response: any) {
    // Do something with response data
    // if (response.headers["set-cookie"] instanceof Array) {
    //   const cookies = response.headers["set-cookie"].forEach(function(c: any) {
    //     cookiejar.setCookie(Cookie.parse(c), response.config.url, function(
    //       err: any,
    //       cookie: any
    //     ) {});
    //   });
    // }
    return response;
  },
  function(error: any) {
    // Do something with response error
    return Promise.reject(error);
  }
);

export default async function(params: IParams) {
  params = Object.assign(
    {
      baseUrl: "",
      url: "",
      data: {},
      type: "GET",
      resType: "JSON",
      cookie: ""
    },
    params
  );

  axios.defaults.baseURL = baseUrl;

  axios.defaults.withCredentials = true;

  axios.defaults.headers = {
    Accept: "application/json",
    "Content-Type": "application/json"
  };
  if (!!params.req) {
    axios.defaults.headers.Cookie = params.req.headers.cookie;
  }

  let ret = null;

  if (params.type === "GET") {
    ret = axios.get(`${params.url}`, {
      params: params.data
    });
  }

  if (params.type === "POST") {
    ret = axios
      .post(`${params.url}`, params.data, {})
      .then(function(res: any) {})
      .catch(function(error: any) {});
  }
  return ret.then((res: any) => {
    console.log(
      cookieParser.JSONCookie(res.headers["set-cookie"]),
      22222,
      res.headers["set-cookie"]
    );
    // console.log(3333, res.headers["set-cookie"]);
    // if (!!res && !!res.headers && !!res.headers["set-cookie"]) {
    //   const cookie = res.headers["set-cookie"];
    //   if (!!params.res && !!params.res.setHeader) {
    //     params.res.setHeader("Set-Cookie", cookie);
    //   }
    // }
    return res;
  });
}
